package com.liws.helloThreadPools.utils;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：liweisheng
 * @date ：2021/12/26 14:01
 * @description：
 */
public class ThreadPoolUtils {
    /**
     * 初始化核心线程数
     */
    private static final int processors = Runtime.getRuntime().availableProcessors();

    /**
     * 线程池最大容量
     */
    private static int maxPoolSize = processors * 2;

    /**
     * 扩容线程数闲置寿命
     */
    private static int keepAliveTime = 2;

    /**
     * 等待队列长度
     */
    private static int waitQueueSize = 1000;

    /**
     * 拒绝策略
     */
    private static RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    /**
     * 线程池实例，懒汉式
     */
    private static ThreadPoolUtils instance = null;

    /**
     * 可重用锁
     */
    private static ReentrantLock lock = new ReentrantLock();


    /**
     * 线程池
     */
    private static ExecutorService fixedThreadPool = null;

    private ThreadPoolUtils() {
        //私有构造器
    }

    public ExecutorService getExecutorService() {
        return fixedThreadPool;
    }

    public static ThreadPoolUtils getInstance() {
        //双重判断加锁
        if (instance == null) {
            lock.lock();
            if (instance == null) {
                instance = new ThreadPoolUtils();
                //使用ThreadPoolExecutor不要使用Executors
                fixedThreadPool = new ThreadPoolExecutor(
                        processors,
                        maxPoolSize,
                        keepAliveTime,
                        TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>(waitQueueSize),
                        Executors.defaultThreadFactory(),
                        handler
                );
            }
            lock.unlock();
        }
        return instance;
    }


}
